<template>
    <div class="product-list-container">
        <!-- 搜索筛选区域 -->
        <div class="search-section">
            <el-card shadow="never" class="search-card">
                <div class="search-content">
                    <div class="search-left">
                        <el-form :model="searchForm" :inline="true" class="search-form">
                            <el-form-item label="名称:">
                                <el-input 
                                    v-model="searchForm.productName" 
                                    placeholder="输入商品名称" 
                                    clearable
                                    style="width: 200px"
                                />
                            </el-form-item>
                            <!-- <el-form-item label="分类:">
                                <el-select 
                                    v-model="searchForm.categoryId" 
                                    placeholder="请选择..." 
                                    clearable
                                    style="width: 150px"
                                >
                                    <el-option label="分类名称" value="category1" />
                                    <el-option label="分类名称2" value="category2" />
                                </el-select>
                            </el-form-item> -->
                            <el-form-item label="发布时间:">
                                <el-date-picker
                                    v-model="searchForm.dateRange"
                                    type="daterange"
                                    range-separator="至"
                                    start-placeholder="请选择日期"
                                    end-placeholder="请选择日期"
                                    format="YYYY-MM-DD"
                                    value-format="YYYY-MM-DD"
                                    style="width: 240px"
                                />
                            </el-form-item>
                        </el-form>
                    </div>
                    <div class="search-right">
                        <el-button type="primary" @click="handleSearch">查询</el-button>
                        <el-button @click="handleReset">重置</el-button>
                    </div>
                </div>
            </el-card>
        </div>

        <!-- 新增商品按钮 -->
        <div class="add-section">
            <el-button type="primary" :icon="CirclePlusFilled" @click="handleAddProduct">新增商品</el-button>
        </div>

        <!-- 数据表格区域 -->
        <div class="table-section">
            <el-card shadow="never" class="table-card">
                <el-table 
                    :data="tableData" 
                    v-loading="loading"
                    stripe
                    border
                    style="width: 100%"
                >
                    <el-table-column type="index" label="序号" width="80" align="center" />
                    <!-- <el-table-column prop="id" label="ID" width="80" align="center" /> -->
                    <el-table-column prop="productName" label="商品名称" />
                    <el-table-column prop="attachments" label="商品主图" width="120" align="center">
                        <template #default="{ row }">
                            <div class="product-image">
                                <img v-if="getMainImage(row)" :src="getMainImage(row)" alt="商品图片" />
                                <div v-else class="image-placeholder">
                                    <el-icon><Picture /></el-icon>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="categoryName" label="商品分类" />
                    <el-table-column prop="price" label="商品价格" align="right">
                        <template #default="{ row }">
                            ¥{{ row.price }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="salesQuantity" label="销售数量" align="center" />
                    <el-table-column prop="status" label="状态" align="center">
                        <template #default="{ row }">
                            <el-tag :type="getStatusType(row.status)">
                                {{ getStatusText(row.status) }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="createTime" label="创建时间" width="180">
                        <template #default="{ row }">
                            {{ formatDateTime(row.createTime) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="200" align="center" fixed="right">
                        <template #default="{ row }">
                            <el-button 
                                v-if="row.productStatus === 1" 
                                type="warning" 
                                size="small" 
                                @click="handleToggleStatus(row)"
                            >
                                下架
                            </el-button>
                            <el-button 
                                v-else 
                                type="success" 
                                size="small" 
                                @click="handleToggleStatus(row)"
                            >
                                上架
                            </el-button>
                            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
                            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>
        </div>

        <!-- 分页区域 -->
        <div class="pagination-section">
            <el-card shadow="never" class="pagination-card">
                <div class="pagination-content">
                    <div class="pagination-info">
                        <span>总共{{ pagination.total }}条记录,当前在第{{ pagination.current }}页</span>
                    </div>
                    <el-pagination
                        v-model:current-page="pagination.current"
                        :page-size="pagination.size"
                        :total="pagination.total"
                        :page-sizes="[10, 20, 50, 100]"
                        layout="prev, pager, next, jumper"
                        @current-change="handlePageChange"
                        @size-change="handleSizeChange"
                    />
                </div>
            </el-card>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Picture } from '@element-plus/icons-vue';
import { getProductPage, deleteProduct } from '@/api/product/product';
import { CirclePlusFilled } from '@element-plus/icons-vue';

// 定义数据类型
interface ProductItem {
    id: string;
    orgId: string;
    productCode: string;
    categoryId: string;
    categoryName: string;
    brandId: string;
    brandName: string;
    brandDescription: string;
    price: number;
    marketPrice: number;
    costPrice: number;
    productStatus: number;
    productStatusName: string;
    isRecommend: number;
    isHot: number;
    isNew: number;
    keywords: string;
    specifications: string;
    salesQuantity: number;
    viewCount: number;
    favoriteCount: number;
    rating: number;
    reviewCount: number;
    createTime: string;
    updateTime: string;
    status: number;
    createBy: string;
    updateBy: string;
    auditStatus: number;
    auditStatusName: string;
    auditOpinion: string;
    auditTime: string;
    auditBy: string;
    auditByName: string;
    productName: string;
    brand: string;
    model: string;
    summary: string;
    detail: string;
    afterSales: string;
    packageList: string;
    specs: Array<{
        id: string;
        productId: string;
        specName: string;
        specValue: string;
        specCode: string;
        priceAdjustment: number;
        stockQuantity: number;
        specImage: string;
        sortOrder: number;
        status: number;
        statusName: string;
        createTime: string;
        updateTime: string;
        i18nList: Array<{
            id: string;
            specId: string;
            language: string;
            specName: string;
            specValue: string;
        }>;
    }>;
    skus: Array<{
        id: string;
        productId: string;
        skuCode: string;
        skuName: string;
        specCombination: string;
        specsJson: string;
        price: number;
        marketPrice: number;
        costPrice: number;
        stockQuantity: number;
        warningStock: number;
        skuImage: string;
        sortOrder: number;
        status: number;
        statusName: string;
        createTime: string;
        language: string;
        updateTime: string;
    }>;
    tags: Array<{
        id: string;
        tagName: string;
        tagCode: string;
        tagColor: string;
        tagIcon: string;
        description: string;
        sortOrder: number;
        status: number;
        statusName: string;
        createTime: string;
        language: string;
        updateTime: string;
    }>;
    attachments: Array<{
        id: string;
        fileName: string;
        fileUrl: string;
        fileSize: number;
        fileExtension: string;
        dataId: string;
        dataType: string;
        attachmentType: string;
        language: string;
        description: string;
        tags: string;
        md5: string;
        sha256: string;
        width: number;
        height: number;
        duration: number;
        thumbnailUrl: string;
        downloadCount: number;
        viewCount: number;
        isPublic: boolean;
        isTemp: boolean;
        expireTime: string;
        createBy: string;
        createTime: string;
        updateBy: string;
        updateTime: string;
        status: number;
    }>;
    isDistribution: number;
    distributionRate: number;
    isFeatured: number;
    language: string;
}

interface ProductPageParams {
    pageNum: number;
    pageSize: number;
    productName?: string;
    categoryId?: string;
    startTime?: string;
    endTime?: string;
}

const router = useRouter();

// 搜索表单
const searchForm = reactive({
    productName: '',
    categoryId: '',
    dateRange: []
});

// 表格数据
const loading = ref(false);
const tableData = ref<ProductItem[]>([]);

// 分页数据
const pagination = reactive({
    current: 1,
    size: 10,
    total: 0
});

// 时间格式化函数
const formatDateTime = (dateTime: string) => {
    if (!dateTime) return '-';
    const date = new Date(dateTime);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
};

// 获取主图
const getMainImage = (row: ProductItem) => {
    if (row.attachments && row.attachments.length > 0) {
        const mainImage = row.attachments.find(att => att.attachmentType === '产品主图');
        return mainImage ? mainImage.fileUrl : row.attachments[0].fileUrl;
    }
    return null;
};

// 获取状态文本
const getStatusText = (status: number) => {
    const statusMap: { [key: number]: string } = {
        0: '禁用',
        1: '启用'
    };
    return statusMap[status] || '未知';
};

// 获取状态类型
const getStatusType = (status: number) => {
    const statusMap: { [key: number]: string } = {
        0: 'danger',   // 禁用
        1: 'success'   // 启用
    };
    return statusMap[status] || 'info';
};

// 获取商品列表
const fetchProductList = async () => {
    try {
        loading.value = true;
        const params: ProductPageParams = {
            pageNum: pagination.current,
            pageSize: pagination.size,
            productName: searchForm.productName || undefined,
            categoryId: searchForm.categoryId || undefined,
            startTime: searchForm.dateRange && searchForm.dateRange[0] ? searchForm.dateRange[0] : undefined,
            endTime: searchForm.dateRange && searchForm.dateRange[1] ? searchForm.dateRange[1] : undefined
        };
        
        const response = await getProductPage(params);
        
        const responseData = response as any;
        if (responseData && responseData.code === 200 && responseData.data) {
            tableData.value = responseData.data.records || responseData.data.list || [];
            pagination.total = responseData.data.total || responseData.data.pageTotal || 0;
        } else {
            const errorMsg = (responseData && (responseData.msg || responseData.message)) || '获取商品列表失败';
            ElMessage.error(errorMsg);
            tableData.value = [];
            pagination.total = 0;
        }
    } catch (error) {
        console.error('获取商品列表失败:', error);
        ElMessage.error('获取商品列表失败');
    } finally {
        loading.value = false;
    }
};

// 搜索方法
const handleSearch = () => {
    pagination.current = 1;
    fetchProductList();
};

// 重置查询方法
const handleReset = () => {
    // 重置搜索表单
    searchForm.productName = '';
    searchForm.categoryId = '';
    searchForm.dateRange = [];
    
    // 重置分页到第一页
    pagination.current = 1;
    
    // 重新加载列表
    fetchProductList();
};

// 分页方法
const handlePageChange = (page: number) => {
    pagination.current = page;
    fetchProductList();
};

const handleSizeChange = (size: number) => {
    pagination.size = size;
    pagination.current = 1;
    fetchProductList();
};

// 新增商品
const handleAddProduct = () => {
    router.push('/product-form');
};

// 编辑商品
const handleEdit = (row: ProductItem) => {
    router.push(`/product-form/${row.id}`);
};

// 切换上下架状态
const handleToggleStatus = (row: ProductItem) => {
    const action = row.productStatus === 1 ? '下架' : '上架';
    ElMessageBox.confirm(
        `确定要${action}商品 "${row.productName}" 吗？`,
        `${action}确认`,
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        // 这里可以调用更新状态的API
        row.productStatus = row.productStatus === 1 ? 0 : 1;
        ElMessage.success(`${action}成功`);
    }).catch(() => {
        ElMessage.info('已取消操作');
    });
};

// 删除商品
const handleDelete = async (row: ProductItem) => {
    try {
        await ElMessageBox.confirm(
            `确定要删除商品 "${row.productName}" 吗？`,
            '删除确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        );
        
        const response = await deleteProduct(row.id);
        
        if (response.data && response.data.success) {
            ElMessage.success('删除成功');
            // 重新加载列表
            fetchProductList();
        } else {
            ElMessage.error(response.data?.message || '删除失败');
        }
    } catch (error) {
        if (error === 'cancel') {
            ElMessage.info('已取消删除');
        } else {
            console.error('删除商品失败:', error);
            ElMessage.error('删除失败');
        }
    }
};

// 页面初始化
onMounted(() => {
    // 加载初始数据
    fetchProductList();
});
</script>

<style scoped>
.product-list-container {
    padding: 20px;
}

/* 搜索区域 */
.search-section {
    margin-bottom: 20px;
}

.search-card {
    border-radius: 8px;
}

.search-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.search-form {
    margin: 0;
}

.search-form .el-form-item {
    margin-bottom: 0;
}

.search-right {
    display: flex;
    align-items: center;
    gap: 12px;
}

.search-right .el-button {
    min-width: 80px;
}

.search-right .el-button + .el-button {
    margin-left: 0;
}

/* 新增按钮区域 */
.add-section {
    margin-bottom: 20px;
}

/* 表格区域 */
.table-section {
    margin-bottom: 20px;
}

.table-card {
    border-radius: 8px;
}

.product-image {
    width: 60px;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    overflow: hidden;
}

.product-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.image-placeholder {
    color: #c0c4cc;
    font-size: 24px;
}

/* 分页区域 */
.pagination-section {
    margin-bottom: 20px;
}

.pagination-card {
    border-radius: 8px;
}

.pagination-content {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-end;
    gap: 20px;
}

.pagination-info {
    color: #606266;
    font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .product-list-container {
        padding: 10px;
    }
    
    .search-content {
        flex-direction: column;
        gap: 15px;
        align-items: stretch;
    }
    
    .search-form {
        display: flex;
        flex-direction: column;
        gap: 10px;
    }
    
    .pagination-content {
        flex-direction: column;
        gap: 15px;
        align-items: center;
    }
}
</style>